import sounddevice
from scipy.io.wavfile import write
from pynput.keyboard import Listener, Key
import threading
import time

# 配置参数
samplerate = 44100
channels = 1
output_file = "recording.wav"
is_recording = False
recording_data = None
stream = None  # 音频流对象

def start_recording():
    """开始录音"""
    global is_recording, stream, recording_data
    if not is_recording:
        print("\n开始录音... (松开F8停止)")
        is_recording = True
        # 创建音频流
        stream = sounddevice.InputStream(samplerate=samplerate, channels=channels, dtype='int16')
        recording_data = []
        stream.start()
        # 持续读取音频数据
        while is_recording:
            data, _ = stream.read(1024)  # 每次读取1024帧
            recording_data.append(data)
            time.sleep(0.01)  # 减少CPU占用

def stop_recording():
    """停止录音并保存"""
    global is_recording, stream
    if is_recording:
        is_recording = False
        if stream:
            stream.stop()
            stream.close()
        print("录音已停止，正在保存...")
        # 合并录音数据并保存
        import numpy as np
        write(output_file, samplerate, np.concatenate(recording_data))
        print(f"保存完成: {output_file}")

def on_press(key):
    """按键按下事件"""
    # 打印按键信息用于调试
    print(f"按下键: {key}")
    try:
        # 两种方式检测F8键
        if key == Key.f8:
            if not is_recording:
                threading.Thread(target=start_recording, daemon=True).start()
    except Exception as e:
        print(f"按键处理错误: {e}")

def on_release(key):
    """按键松开事件"""
    print(f"松开键: {key}")
    try:
        if key == Key.f8:
            stop_recording()
    except Exception as e:
        print(f"释放处理错误: {e}")

if __name__ == "__main__":
    print("按F8开始录音，松开F8停止录音")
    print("按Esc退出程序")
    print("---调试信息---")
    
    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()
